/*-------------------------- +
      获取id, class, tagName
     +-------------------------- */
var get = {
    byId: function(id) {
        return typeof id === "string" ? document.getElementById(id) : id
    },
    byClass: function(sClass, oParent) {
        var aClass = [];
        var reClass = new RegExp("(^| )" + sClass + "( |$)");
        var aElem = this.byTagName("*", oParent);
        for (var i = 0; i < aElem.length; i++) reClass.test(aElem[i].className) && aClass.push(aElem[i]);
        return aClass
    },
    byTagName: function(elem, obj) {
        return (obj || document).getElementsByTagName(elem);
    }
};

/*-------------------------- +
 事件绑定, 删除
 +-------------------------- */
var EventUtil = {
    addHandler: function(oElement, sEvent, fnHandler) {
        oElement.addEventListener ? oElement.addEventListener(sEvent, fnHandler, false) : (oElement["_" + sEvent + fnHandler] = fnHandler, oElement[sEvent + fnHandler] = function() {
            oElement["_" + sEvent + fnHandler]()
        }, oElement.attachEvent("on" + sEvent, oElement[sEvent + fnHandler]))
    },
    removeHandler: function(oElement, sEvent, fnHandler) {
        oElement.removeEventListener ? oElement.removeEventListener(sEvent, fnHandler, false) : oElement.detachEvent("on" + sEvent, oElement[sEvent + fnHandler])
    },
    addLoadHandler: function(fnHandler) {
        this.addHandler(window, "load", fnHandler)
    }
};

/*-------------------------- +
 设置css样式
 读取css样式
 +-------------------------- */
function css(obj, attr, value) {
    switch (arguments.length) {
        case 2:
            if (typeof arguments[1] == "object") {
                for (var i in attr) i == "opacity" ? (obj.style["filter"] = "alpha(opacity=" + attr[i] + ")", obj.style[i] = attr[i] / 100) : obj.style[i] = attr[i];
            } else {
                return obj.currentStyle ? obj.currentStyle[attr] : getComputedStyle(obj, null)[attr]
            }
            break;
        case 3:
            attr == "opacity" ? (obj.style["filter"] = "alpha(opacity=" + value + ")", obj.style[attr] = value / 100) : obj.style[attr] = value;
            break;
    }
};

EventUtil.addLoadHandler(function() {
    var oMsgBox = get.byId("msgBox");
    var oConBox = get.byId("conBox");
    var oSendBtn = get.byId("sendBtn");
    var oMaxNum = get.byClass("maxNum")[0];
    var oCountTxt = get.byClass("countTxt")[0];
    var oList = get.byClass("list")[0];
    var oUl = get.byTagName("ul", oList)[0];
    var aLi = get.byTagName("li", oList);
    var aFtxt = get.byClass("f-text", oMsgBox);
    var maxNum = 140;
    //事件绑定, 判断字符输入
    EventUtil.addHandler(oConBox, "keyup", confine);
    EventUtil.addHandler(oConBox, "focus", confine);
    EventUtil.addHandler(oConBox, "change", confine);

    //为广播按钮绑定发送事件
    EventUtil.addHandler(oSendBtn, "click", addMessage);
    //输入字符限制
    function confine() {
        var iLen = 0;
        for (i = 0; i < oConBox.value.length; i++) iLen += /[^\x00-\xff]/g.test(oConBox.value.charAt(i)) ? 1 : 0.5;
        oMaxNum.innerHTML = Math.abs(maxNum - Math.floor(iLen));
        maxNum - Math.floor(iLen) >= 0 ? (css(oMaxNum, "color", ""), oCountTxt.innerHTML = "\u8fd8\u80fd\u8f93\u5165", bSend = true) : (css(oMaxNum, "color", "#f60"), oCountTxt.innerHTML = "\u5df2\u8d85\u51fa", bSend = false)
    }
   //加载即调用
    confine();
})




var httpUrl = 'http://xtsgms.zhinengjianshe.com/sgms';


/**
 * 页面加载
 */
$(function(){
    loadMessage();
})

/**
 * 添加留言
 */
function addMessage(){
    var result={};
    $("#add_message_form").serializeArray().map(function (x) {
        result[x.name] = x.value;
    });
    var content = result.content;
    var iLen = 0;
    for (i = 0; i < content.length; i++) {
        iLen += /[^\x00-\xff]/g.test(content.charAt(i)) ? 1 : 0.5;
    }
    if(iLen>140){
       alert("留言字数已超出最大字数")
    }else{
        $.ajax({
            type:"POST",
            url:httpUrl + "/schedule/messageBoard/add",
            dataType:"json",
            contentType:"application/json;charset=utf-8",
            data:JSON.stringify(result),
            success:function(data){
                if(data && data.success){
                    $("#add_message_form")[0].reset();
                    alert(data.message);
                    loadRows(data.data);
                }
            }
        });
    }

}


/**
 * 加载留言列表
 *
 */
function loadMessage() {

    var param = {
        mapParams:{},
        page:1,
        size:10,
    };
    $.ajax({
        type: "POST",
        url: httpUrl+"/schedule/messageBoard/query",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        data: JSON.stringify(param),
        success: function (data) {
          if(data.rows && !data.total >0){
              $("#disabledli").css('display', 'block');
          }else{
              $.each(data.rows,function(index,message){
                loadRows(message);
                  $("#disabledli").css('display', 'none');
              })
          }
        }
    });
}


function loadRows(message){
    var oMsgBox = get.byId("msgBox");
    var oList = get.byClass("list")[0];
    var oUl = get.byTagName("ul", oList)[0];
    var aLi = get.byTagName("li", oList);
    var oLi = document.createElement("li");
    var timer = null;
    var oDate = new Date(message.createdTime);
    message.creatorName=(message.creatorName && null != message.creatorName && ''!= message.creatorName)?message.creatorName:'匿名';
    oLi.innerHTML = "<div class=\"content\">\
                                <div class=\"userName\"><a href=\"javascript:;\">" + message.creatorName + "</a> </div>\
                                <div class=\"msgInfo\"><span>" + format(oDate.getMonth() + 1) + "\u6708" + format(oDate.getDate()) + "\u65e5 " + format(oDate.getHours()) + ":" + format(oDate.getMinutes()) + "</span></div>\
                                \<div class=\"times\"><p>" + message.content.replace(/<[^>]*>|&nbsp;/ig, "") + "</p></div>\
                             </div>";
    // <a class=\"del\" href=\"javascript:;\">\u5220\u9664</a>
    //插入元素
    aLi.length ? oUl.insertBefore(oLi, aLi[0]) : oUl.appendChild(oLi);

    //重置表单
    get.byTagName("form", oMsgBox)[0].reset();
  /*  for (i = 0; i < aImg.length; i++) aImg[i].className = "";
    aImg[0].className = "current";*/

    //将元素高度保存
    var iHeight = oLi.clientHeight - parseFloat(css(oLi, "paddingTop")) - parseFloat(css(oLi, "paddingBottom"));
    var alpah = count = 0;
    css(oLi, {
        "opacity": "0",
        "height": "0"
    });
    timer = setInterval(function() {
        css(oLi, {
            "display": "block",
            "opacity": "0",
            "height": (count += 8) + "px"
        });
        if (count > iHeight) {
            clearInterval(timer);
            css(oLi, "height", iHeight + "px");
            timer = setInterval(function() {
                css(oLi, "opacity", (alpah += 10));
                alpah > 100 && (clearInterval(timer), css(oLi, "opacity", 100))
            }, 30)
        }
    }, 30);
    //调用鼠标划过/离开样式
    liHover();
    //调用删除函数
    // delLi();
}

//li鼠标划过/离开处理函数
function liHover() {
    var oList = get.byClass("list")[0];
    var aLi = get.byTagName("li", oList);
    for (i = 0; i < aLi.length; i++) {
        //li鼠标划过样式
        EventUtil.addHandler(aLi[i], "mouseover", function(event) {
            this.className = "hover";
            oTmp = get.byClass("times", this)[0];
            var aA = get.byTagName("a", oTmp);
            if (!aA.length) {
                var oA = document.createElement("a");
                // oA.innerHTML = "删除";
                // oA.className = "del";
                oA.href = "javascript:;";
                oTmp.appendChild(oA)
            } else {
                aA[0].style.display = "block";
            }
        });

        //li鼠标离开样式
        EventUtil.addHandler(aLi[i], "mouseout", function() {
            this.className = "";
            var oA = get.byTagName("a", get.byClass("times", this)[0])[0];
            oA.style.display = "none"
        })
    }
}
liHover();


//格式化时间, 如果为一位数时补0
function format(str) {
    return str.toString().replace(/^(\d)$/, "0$1")
}





